package com.jd.goods.service.impl;

import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.jd.common.util.JsonUtils;
import com.jd.goods.mapper.GoodsCategoryMapper;
import com.jd.goods.pojo.GoodsCatData;
import com.jd.goods.pojo.GoodsCatNode;
import com.jd.goods.pojo.GoodsCategory;
import com.jd.goods.service.GoodsCategoryService;


@Service("goodsCategoryService")
@Path("goodscat")
public class GoodsCategoryServiceImpl implements GoodsCategoryService {
	@Autowired
	private GoodsCategoryMapper goodsCategoryMapper;

	@Override
	public List<GoodsCategory> getGoodsCatsByParentId(Long parentId) {
		return goodsCategoryMapper.getGoodsCategoryByParentId(parentId);
	}

	@GET
	@Path("data")
	@Produces(ContentType.APPLICATION_JSON_UTF_8)
	public Object getGoodsCatData(@QueryParam("callback")String callback) {
		GoodsCatData data = new GoodsCatData();
		//获取所有的商品分类信息
		data.setData(getItemCatNodeByParentId(0L));
		return callback+"("+JsonUtils.objectToJson(data)+")";
	}

	// 递归查询单个节点下的所有子节点,只查询14条根节点
	private List getItemCatNodeByParentId(long parentId) {
		// 定义一个计数器
		int count = 0;

		List nodes = new ArrayList();
		// 首先查询数据库
		List<GoodsCategory> itemCats = goodsCategoryMapper.getGoodsCategoryByParentId(parentId);
		// 对象转换
		for (GoodsCategory cat : itemCats) {
			// 如果count=14时，跳出循环
			if (count == 14) {
				break;
			}
			// 先判断是否是叶子节点
			if (cat.getIsParent()) {
				GoodsCatNode node = new GoodsCatNode();
				node.setU("/products/" + cat.getId() + ".html");
				// 判断是否是根节点
				if (parentId == 0) {
					node.setN("<a href='/products/" + cat.getId() + ".html'>"
							+ cat.getName() + "</a>");
					count++;
				} else {
					node.setN(cat.getName());
				}
				// 递归调用自己
				node.setI(getItemCatNodeByParentId(cat.getId()));
				nodes.add(node);
			} else {
				// 添加一个字符串
				String s = "/products/" + cat.getId() + ".html|"
						+ cat.getName();
				nodes.add(s);
			}
		}
		return nodes;
	}
}
